package com.eii.resubmit.aop.request.checker;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 阻塞型重复请求检查GUAVACACHE实现
 * @author eii
 * @time 2020/11/28 11:38 下午
 */
@Component("manualGuavaChecker")
public class ManualGuavaChecker implements ManualChecker {

    private Cache<String, Boolean> cache;

    private ReentrantLock reentrantLock = new ReentrantLock(true);
    /**
     * 超时时间
     */
    private static final Integer TIMEOUT = 60000;
    /**
     * 默认单位:毫秒
     */
    public static final TimeUnit TIME_UNIT = TimeUnit.MILLISECONDS;

    @Autowired
    public ManualGuavaChecker() {
        cache = CacheBuilder.newBuilder()
                .expireAfterAccess(TIMEOUT, TIME_UNIT).build();
    }

    @Override
    public boolean lock(String key) {
        //若cache key对应的value 为nul 说明没有被设置，则新增该key，此时锁成功
        return Objects.isNull(cache.asMap().putIfAbsent(key, true));
    }

    @Override
    public void free(String key) {
        cache.invalidate(key);
    }

    @Override
    public boolean check(String key) {
        return cache.getIfPresent(key) != null;
    }
}
